package com.zjxf.controller;

import com.alibaba.fastjson.JSONObject;
import com.zjxf.base.bean.po.CmsNews;
import com.zjxf.base.bean.ro.RoCmsNews;
import com.zjxf.base.bean.vo.VoCmsNews;
import com.zjxf.base.common.JSONResponse;
import com.zjxf.base.common.OperationException;
import com.zjxf.base.common.SysConst;
import com.zjxf.controller.common.BaseController;
import com.zjxf.service.CmsNewsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * 新闻
 *
 * @author ZhangWei
 * @date 2021/4/6/006 10:48
 */
@Validated
@RestController
@AllArgsConstructor
@Api(tags = "新闻")
@RequestMapping("/news/")
public class CmsNewsController extends BaseController {

    private final CmsNewsService cmsNewsService;

    @ApiOperation(value = "添加或修改")
    @PostMapping("addOrUpdate")
    public JSONResponse addOrUpdate(@Valid @RequestBody VoCmsNews.addOrUpdate vo) {
        cmsNewsService.addOrUpdate(vo);
        return JSONResponse.success(SysConst.SUCCESS);
    }

    @ApiOperation(value = "删除")
    @PostMapping("delete")
    public JSONResponse delete(@NotNull(message = "请填写新闻id") @RequestParam Long id) throws OperationException {
        cmsNewsService.delete(id);
        return JSONResponse.success(SysConst.SUCCESS);
    }

    @ApiOperation(value = "回显")
    @PostMapping("get")
    public JSONResponse get(@NotNull(message = "请填写新闻id") @RequestParam Long id) throws OperationException {
        CmsNews cmsNews = cmsNewsService.getEntity(id);
        RoCmsNews.Details details = cmsNewsService.getEntityRo(cmsNews);
        return JSONResponse.success(details);
    }

    @ApiOperation(value = "分页")
    @PostMapping("page")
    public JSONResponse page(@Valid @RequestBody VoCmsNews.filter filter) {
        Page<CmsNews> cmsNewsPage = cmsNewsService.page(filter);
        JSONObject jsonData = cmsNewsService.pageRo(cmsNewsPage);
        return JSONResponse.success(jsonData);
    }

}
